﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;

namespace AjaxControlFramework
{
	public class DotNetJsonCallbackSerializer : CallbackSerializer
	{
        //------// Fields \\------------------------------------------------\\
        public static readonly Regex JavascriptDateRegex = new Regex("\"\\\\/Date\\((\\d+)\\)\\\\/\"");


        protected JavaScriptSerializer Serializer = new JavaScriptSerializer(new SimpleTypeResolver()) { MaxJsonLength = 5000000 };
        //------\\ Fields //------------------------------------------------//



		//------// Methods \\-----------------------------------------------\\
		public override string SerializeCallbackResult(Dictionary<string, object> callbackResult)
		{
			string jsonResult = Serializer.Serialize(callbackResult);
            return JavascriptDateRegex.Replace(jsonResult, "new Date($1)");
		}


        public override string SerializeException(Exception exception)
        {
            Serializer.RegisterConverters(new JavaScriptConverter[] { new ExceptionJavascriptConverter() });
            return Serializer.Serialize(exception);
        }


        public override string SerializeObject(object obj)
        {
            return Serializer.Serialize(obj);
        }


        public override object DeserializeObject(string jsonString)
        {
            return Serializer.DeserializeObject(jsonString);
        }


		public override T DeserializeObject<T>(string strObj)
		{
            return Serializer.Deserialize<T>(strObj);
		}
		//------\\ Methods //-----------------------------------------------//
	}
}
